package com.zjk.toolkit.hystrix.aspect;

import com.zjk.toolkit.hystrix.annotation.DoHystrix;
import com.zjk.toolkit.hystrix.service.impl.IHystrixServiceImpl;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DoHystrixAspect {

    @Pointcut("@annotation(com.zjk.toolkit.hystrix.annotation.DoHystrix)")
    public void aop(){

    }

    @Around("aop() && @annotation(doGoven)")
    public Object doHystrix(ProceedingJoinPoint joinPoint, DoHystrix doGoven) throws Throwable {
        IHystrixServiceImpl hystrixService = new IHystrixServiceImpl(doGoven.timeout());
        return hystrixService.access(joinPoint, getMethod(joinPoint), doGoven, joinPoint.getArgs());
    }

    private Method getMethod(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        return joinPoint.getTarget().getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
    }
}
